package cn.cvs.controller;



import cn.cvs.pojo.Blog;
import cn.cvs.pojo.SysUser;
import cn.cvs.pojo.User;
import cn.cvs.service.user.UserService;
import cn.cvs.utils.Constants;
import cn.cvs.utils.PageSupport;
import com.alibaba.fastjson.JSON;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/user")
public class UserController extends  BaseController{

    private Logger logger = Logger.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public String doLoginHome(@RequestParam String username, @RequestParam String password,
                              HttpServletRequest request, HttpSession session) throws Exception{
        //调用service方法，进行用户匹配
        User user = userService.login(username,password);
        if(null != user){//登录成功
            session.setAttribute(Constants.USER_SESSION, user);
            return "redirect:/sys/home";
        }else{
            request.setAttribute("error", "用户名或密码不正确");
            return "loginHome";
        }
    }

    @RequestMapping(value="/toList")
    public String queryPageList(Model model,
                                @RequestParam(value = "name",required = false) String name,
                                @RequestParam(value ="pageIndex", defaultValue = "1") Integer pageIndex ) {
        //设置页面容量
        Integer pageSize = Constants.pageSize;

        int totalCount = userService.count(name);

        PageSupport pages=new PageSupport();
        pages.setCurrentPageNo(pageIndex);
        pages.setPageSize(pageSize);
        pages.setTotalCount(totalCount);
        int totalPageCount = pages.getTotalPageCount();

        List<User> users = userService.list(name, pageIndex, pageSize);

        if(pageIndex > totalPageCount){
            pageIndex = totalPageCount;
        }

        model.addAttribute("userList", users);
        model.addAttribute("totalPageCount", totalPageCount);
        model.addAttribute("totalCount", totalCount);
        model.addAttribute("currentPageNo", pageIndex);

        return "user/list";
    }

    @RequestMapping("/toAdd")
    public String toAdd(){
        return "user/add";
    }

    @RequestMapping("/view/{id}")
    public String toU(Model model,@PathVariable Integer id){
        User user = userService.getUserById(id);
        model.addAttribute("user",user);
        return "user/toUpdate";
    }

    @RequestMapping("/del/{id}")
    @ResponseBody
    public String toU(@PathVariable Integer id){
        Map<String,String> map = new HashMap<>();
        int count = userService.deleteById(id);
        if (count > 0) {
            map.put("result","true");
        } else {
            map.put("result","false");
        }
        return JSON.toJSONString(map);
    }

    @PostMapping("/toSave")
    public String addUserSave(User user,HttpSession session,HttpServletRequest request
            ,@RequestParam(value ="workPic", required = false) MultipartFile workPic){
        String idPicPath = null;
        String workPicPath = null;
        String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles");


        //判断文件是否为空(工作证照)
        if(!workPic.isEmpty()){
            String oldFileName = workPic.getOriginalFilename();//原文件名
            logger.info("uploadFile oldFileName ============== > "+oldFileName);
            String prefix=FilenameUtils.getExtension(oldFileName);//原文件后缀
            logger.debug("uploadFile prefix============> " + prefix);
            int filesize = 500000;
            logger.debug("uploadFile size============> " + workPic.getSize());
            if(workPic.getSize() >  filesize){//上传大小不得超过 500k
                request.setAttribute("uploadWpError", " * 上传大小不得超过 500k");
                return "useradd";
            }else if(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
                    || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")){//上传图片格式不正确
                String fileName = System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_Personal.jpg";
                logger.debug("new fileName======== " + workPic.getName());
                File targetFile = new File(path, fileName);
                if(!targetFile.exists()){
                    targetFile.mkdirs();
                }
                //保存
                try {
                    workPic.transferTo(targetFile);
                } catch (Exception e) {
                    e.printStackTrace();
                    request.setAttribute("uploadWpError", " * 上传失败！");
                    return "sysUser/add";
                }
                workPicPath = fileName;
            }else{
                request.setAttribute("uploadWpError", " * 上传图片格式不正确");
                return "sysUser/add";
            }
        }

        try{

            user.setPic(workPicPath);
            int i = userService.registerUser(user);
            if (i > 0) {
                return "redirect:/user/toList";
            }

        }catch (Exception e){
            e.printStackTrace();
            logger.error("保存用户信息失败");
        }
        return "user/add";
    }


    @PostMapping("/toUpdate")
    public String toUpdate(User user,HttpSession session,HttpServletRequest request
            ,@RequestParam(value ="workPic", required = false) MultipartFile workPic){
        String idPicPath = null;
        String workPicPath = null;
        String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles");


        //判断文件是否为空(工作证照)
        if(!workPic.isEmpty()){
            String oldFileName = workPic.getOriginalFilename();//原文件名
            logger.info("uploadFile oldFileName ============== > "+oldFileName);
            String prefix=FilenameUtils.getExtension(oldFileName);//原文件后缀
            logger.debug("uploadFile prefix============> " + prefix);
            int filesize = 500000;
            logger.debug("uploadFile size============> " + workPic.getSize());
            if(workPic.getSize() >  filesize){//上传大小不得超过 500k
                request.setAttribute("uploadWpError", " * 上传大小不得超过 500k");
                return "useradd";
            }else if(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
                    || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")){//上传图片格式不正确
                String fileName = System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_Personal.jpg";
                logger.debug("new fileName======== " + workPic.getName());
                File targetFile = new File(path, fileName);
                if(!targetFile.exists()){
                    targetFile.mkdirs();
                }
                //保存
                try {
                    workPic.transferTo(targetFile);
                } catch (Exception e) {
                    e.printStackTrace();
                    request.setAttribute("uploadWpError", " * 上传失败！");
                    return "sysUser/add";
                }
                workPicPath = fileName;
            }else{
                request.setAttribute("uploadWpError", " * 上传图片格式不正确");
                return "sysUser/add";
            }
        }

        try{

            user.setPic(workPicPath);
            int i = userService.updateUser(user);
            if (i > 0) {
                return "redirect:/user/toList";
            }

        }catch (Exception e){
            e.printStackTrace();
            logger.error("保存用户信息失败");
        }
        return "user/add";
    }




    /**
     * 退出登录
     * @param session
     * @return
     */
    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute(Constants.USER_SESSION);
        return "loginHome";
    }


    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String showRegisterForm(Model model) {
        model.addAttribute("user", new User());
        return "user/register";
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {

        return "loginHome";
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String registerUser(@ModelAttribute("user") User user) {
        MultipartFile file = user.getFile();
        if (!file.isEmpty()) {
            try {
                String originalFilename = file.getOriginalFilename();
                String newFileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
                File dest = new File("upload/" + newFileName);
                file.transferTo(dest);
                user.setPic(newFileName);
            } catch (IOException e) {
                e.printStackTrace();
                return "registerFailed";
            }
        }
        int result = userService.registerUser(user);
        if (result > 0) {
            return "redirect:/user/registerSuccess";
        } else {
            return "registerFailed";
        }
    }

    @RequestMapping(value = "/update", method = RequestMethod.GET)
    public String showUpdateForm(Model model,HttpSession session) {
        User user = (User) session.getAttribute(Constants.USER_SESSION);
        model.addAttribute("user", user);
        return "user/update";
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String updateUser(@ModelAttribute("user") User user) {
        MultipartFile file = user.getFile();
        if (!file.isEmpty()) {
            try {
                String originalFilename = file.getOriginalFilename();
                String newFileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
                File dest = new File("upload/" + newFileName);
                file.transferTo(dest);
                user.setPic(newFileName);
            } catch (IOException e) {
                e.printStackTrace();
                return "updateFailed";
            }
        }
        int result = userService.updateUser(user);
        if (result > 0) {
            return "redirect:/user/updateSuccess";
        } else {
            return "updateFailed";
        }
    }

    @RequestMapping("/registerSuccess")
    public String registerSuccess() {
        return "user/registerSuccess";
    }

    @RequestMapping("/updateSuccess")
    public String updateSuccess() {
        return "user/updateSuccess";
    }
}